﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Traceability_2203.Bais.Api.Application.Commands.User;
using Traceability_2203.Bais.Api.Common;
using Traceability_2203.Common.Dtos;
using Traceability_2203.Common.Infrastructure.Interfaces;
using Traceability_2203.Common.Infrastructure.Repositories;

namespace Traceability_2203.Bais.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UsersController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IMediator mediator;
        private readonly IIdentityService identityService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        public UsersController(IMediator mediator, IConfiguration configuration, IIdentityService identityService)
        {
            this.mediator = mediator;
            this.configuration = configuration;
            this.identityService = identityService;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost("AddUser")]
        [AllowAnonymous]
        public async Task<Result> AddUser(UserCreateCommand cmd)
        {
            return await mediator.Send(cmd);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost("UpdateUser")]
        public async Task<Result> UpdateUser(UserUpdateCommand cmd)
        {
            return await mediator.Send(cmd);
        }

        /// <summary>
        /// 显示查询用户
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost("SearchUser")]
        public async Task<Result<List<UserDto>>> SearchUser(UserSearchCommand cmd)
        {

            var a = identityService.UserName;
            var b = identityService.UserId;


            var userName = User.FindFirst("UserName").Value;
            var userId = User.FindFirst("UserId").Value;


            return await mediator.Send(cmd);
        }

        [HttpGet("Login")]
        [AllowAnonymous] //允许匿名访问
        public async Task<string> Login(string userName, string userPwd)
        {
            //登录成功 生成 Token令牌
            var token = CreateTokenString(userName);
            return token;
        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString(string userName)
        {
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("Email","pmandy@163.com"),
                new Claim("Phone","123456"),
                new Claim("UserId","1"),
                new Claim("UserName",userName),
            };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,//发行者
                audience: jwtSettings.Audience,//受众者
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

        /// <summary>
        /// 解析token 载荷
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("GetTokenClaim")]
        [AllowAnonymous]
        public async Task<UserDto> GetTokenClaim(string token)
        {
            //替换
            token = token.Replace("Bearer ", "");
            //声明jwt Handler
            var jwtHandler = new JwtSecurityTokenHandler();
            //读取token 获取载荷 
            var payload = jwtHandler.ReadJwtToken(token).Payload;
            // 载荷里有 自定义的声明 
            var claims = payload.Claims;
            var userId = claims.Where(x => x.Type == "UserId").FirstOrDefault();
            var userName = claims.Where(x => x.Type == "UserName").FirstOrDefault();

            var result = new UserDto()
            {
                UserId = int.Parse(userId.Value),
                UserName = userName.Value,
            };
            return result;
        }
    }
}
